package com.waijiaojun.tpo.service;

import com.waijiaojun.tpo.comm.Delete;
import com.waijiaojun.tpo.comm.PayStatus;
import com.waijiaojun.tpo.entity.GoodsOrder;
import com.waijiaojun.tpo.repository.GoodsOrderDao;
import com.waijiaojun.tpo.repository.weixin.WeixinScanLogDao;
import com.waijiaojun.tpo.service.weixin.WeixinPayService;
import com.waijiaojun.tpo.utils.Constants;
import com.waijiaojun.tpo.utils.DateUtil;
import com.waijiaojun.tpo.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Component
public class GoodsOrderService {

    @Autowired
    private GoodsOrderDao goodsOrderDao;

    @Autowired
    private WeixinPayService weixinPayService;

    @Autowired
    private WeixinScanLogDao weixinScanLogDao;

    @Autowired
    private GoodsOrderService goodsOrderService;

    public void save(GoodsOrder pojo) {
        goodsOrderDao.save(pojo);
    }

    public void update(GoodsOrder pojo) {
        goodsOrderDao.update(pojo);
    }

    /**
     * 创建【未付款】订单（怎么验证订单数据的正确性？订单在支付之前创建，支付后，支付金额需要与订单实付金额进行比较。）
     * <p>
     * <p>
     * 保存7个表：1订单、2订单详情、3售后地址、4佣金记录、5佣金记录log、6佣金统计、7佣金统计log
     * </p>
     *
     * @param goodsOrder
     * @return BrandWCPayRequestVo
     */
    @Transactional
    public Map<String, String> createOrder(GoodsOrder goodsOrder) {
        // 1. 创建订单
        // GoodsOrder order = new GoodsOrder();
        // 创建订单编号
        String orderCode = getOrderCode();
        goodsOrder.setDeleted(Delete.Enabled);
        goodsOrder.setWeixinPublicId(Constants.publicId);
        goodsOrder.setOrderCode(orderCode);// 订单号

        // 是否扫码，扫码后使用优惠价格
        String openid=UserUtil.getCurrentUserOpenId();
        int isScanQrCode = goodsOrderService.isScanQrCode(openid);// 是否扫码：0否，1是
        if(isScanQrCode==0) {
            goodsOrder.setMoney(Constants.goodsPrice);// 订单金额
            goodsOrder.setPayMoney(Constants.goodsPrice);// 实际支付金额
        }else{
            // 扫码后使用优惠价格
            goodsOrder.setMoney(Constants.goodsActivityPrice);// 订单金额
            goodsOrder.setPayMoney(Constants.goodsActivityPrice);// 实际支付金额
        }
        goodsOrder.setPayStatus(PayStatus.UNPAY);// 支付状态【未付款】（支付成功后才能改为‘已付款’）
        goodsOrder.setOpenid(UserUtil.getCurrentUserOpenId());
        goodsOrder.setCreateDate(new Date());
        goodsOrderDao.save(goodsOrder);

        // 微信支付，调用微信统一下单接口，并返回H5接口所需数据
        Map<String, String> params = weixinPayService.publicPay(goodsOrder, UserUtil.getCurrentUserOpenId());
        return params;
    }


    /**
     * @return 订单编号<br/><br/>
     * 格式：weixinID + "-" + "yyyyMMddhhmmssSSS" + "五位随机数"<br/><br/>
     * 例如：120150601220315567000860
     */
    public String getOrderCode() {
        Random r = new Random();
        DecimalFormat df = new DecimalFormat("00000000.##");
        String orderCode = Constants.publicId + "" + DateUtil.sdf_4.format(new Date()) + "-" + df.format(r.nextInt(100000000));

        return orderCode;
    }

    public int isPay(String openid) {
        int isPay = 0;// 0 未购买，1已购买
        List<GoodsOrder> list = goodsOrderDao.getByOpenid(openid);
        if (list != null && list.size() > 0) {
            for (GoodsOrder order : list) {
                int n = order.getPayStatus().intValue();
                if (n == 1) {
                    isPay = 1;
                    break;
                }
            }
        }
        return isPay;
    }

    public int isScanQrCode(String openid) {
        int count = weixinScanLogDao.isScanQrCode(openid);
        return count == 0 ? 0 : 1;
    }
}
